//
//  Map.h
//  Prism
//
//  Created by Bas du Pre on 26-05-11.
//  Copyright 2011 UU. All rights reserved.
//

#pragma once

#include "global.h"
#include "functions.h"

#include "LinkedList.h"

namespace Prism {
    
    template <typename Key, typename Value>
    class Map : public PObject {
        List<Key> keys;
        List<Value> values;
        
    public:
        Map() {
            
        }
        virtual ~Map() {
            
        }
        
        bool empty() const { return ( keys.empty() ); }
        unsigned int length() { return keys.size(); }
        
        Value& at(Key k) {
            for (unsigned int i = 0; i < keys.length(); i++) {
                if (keys[i] == k) return values[i];
            }
            
            keys.pushBack(k);
            values.pushBack(0);
            return values[values.length() - 1];
        }
        
        bool keyExist(Key k) {
            for (unsigned int i = 0; i < keys.length(); i++) {
                if (keys[i] == k) return true;
            }
            return false;
        }
        
        Value& operator[] (Key k) {
            return at(k);
        }
        
        void set(Key key, Value value) {
            for (unsigned int i = 0; i < keys.length(); i++) {
                if (keys[i] == key) {
                    values[i] = value;
                    return;
                }
            }
            keys.pushBack(key);
            values.pushBack(value);
        }
        
        void remove(Key key) {
            for (unsigned int i = 0; i < keys.length(); i++) {
                if (keys[i] == key) {
                    keys.removeAt(i);
                    values.removeAt(i);
                    return;
                }
            }
            PRISM_ERROR("Cannot remove key because it does not exist.");
        }
        
        void removeValues(Value value) {
            for (unsigned int i = 0; i < values.length(); i++) {
                if (values[i] == value) {
                    keys.removeAt(i);
                    values.removeAt(i);
                }
            }
        }
        
        virtual String toString() {
            String str = "[Map {";
            for (unsigned int i = 0; i < keys.length(); i++) {
                str += objectToString(keys.at(i));
                str += " => ";
                str += objectToString(values.at(i));
                
                if (i < keys.length() - 1)
                    str += ", ";
            }
            str += "}]";
            return str;
        }
    
    };
    
}